package org.example.managere.controller.feibiao;

import lombok.RequiredArgsConstructor;
import org.example.managere.dto.feibiao.AmArchivesDegradationDto;
import org.example.managere.service.feibiao.AmArchivesDegradationService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 电机性能退化数据控制器
 */
@RestController
@RequestMapping("/api/feibiao/degradation")
@RequiredArgsConstructor
public class AmArchivesDegradationController {

    private final AmArchivesDegradationService degradationService;

    /**
     * 获取所有性能退化记录（分页）
     */
    @GetMapping
    public ResponseEntity<?> getAllDegradation(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String sort,
            @RequestParam(required = false) String motorId) {
        try {
            Pageable pageable;
            if (sort != null && !sort.isEmpty()) {
                String[] sortParams = sort.split(",");
                String sortField = sortParams[0];
                Sort.Direction direction = (sortParams.length > 1 && sortParams[1].equalsIgnoreCase("desc"))
                        ? Sort.Direction.DESC : Sort.Direction.ASC;
                pageable = PageRequest.of(page, size, Sort.by(direction, sortField));
            } else {
                pageable = PageRequest.of(page, size);
            }
            return ResponseEntity.ok(degradationService.findAll(motorId, pageable));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", e.getMessage() != null ? e.getMessage() : "处理请求时发生未知错误"));
        }
    }

    /**
     * 根据ID获取性能退化记录
     */
    @GetMapping("/{degradationId}")
    public ResponseEntity<?> getDegradationById(@PathVariable Integer degradationId) {
        try {
            return degradationService.findById(degradationId)
                    .map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", e.getMessage() != null ? e.getMessage() : "处理请求时发生未知错误"));
        }
    }

    /**
     * 创建性能退化记录
     */
    @PostMapping
    public ResponseEntity<?> createDegradation(@RequestBody AmArchivesDegradationDto degradationDto) {
        try {
            return new ResponseEntity<>(degradationService.save(degradationDto), HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", e.getMessage() != null ? e.getMessage() : "创建性能退化记录时发生错误"));
        }
    }

    /**
     * 更新性能退化记录
     */
    @PutMapping("/{degradationId}")
    public ResponseEntity<?> updateDegradation(
            @PathVariable Integer degradationId,
            @RequestBody AmArchivesDegradationDto degradationDto) {
        try {
            // 确保路径ID与请求体ID匹配
            if (degradationDto.getDegradationId() != null && !degradationId.equals(degradationDto.getDegradationId())) {
                return ResponseEntity.badRequest().body(Map.of("error", "路径ID与请求体ID不匹配"));
            }
            degradationDto.setDegradationId(degradationId);
            return ResponseEntity.ok(degradationService.update(degradationDto));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", e.getMessage() != null ? e.getMessage() : "更新性能退化记录时发生错误"));
        }
    }

    /**
     * 删除性能退化记录
     */
    @DeleteMapping("/{degradationId}")
    public ResponseEntity<?> deleteDegradation(@PathVariable Integer degradationId) {
        try {
            degradationService.deleteById(degradationId);
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", e.getMessage() != null ? e.getMessage() : "删除性能退化记录时发生错误"));
        }
    }

    /**
     * 根据电机ID查询性能退化记录
     */
    @GetMapping("/by-motor")
    public ResponseEntity<?> findByMotorId(@RequestParam String motorId) {
        try {
            return ResponseEntity.ok(degradationService.findByMotorId(motorId));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", e.getMessage() != null ? e.getMessage() : "查询性能退化记录时发生错误"));
        }
    }

    /**
     * 根据测量时间范围查询性能退化记录
     */
    @GetMapping("/by-time-range")
    public ResponseEntity<?> findByTimeRange(
            @RequestParam Long startTime,
            @RequestParam Long endTime) {
        try {
            Date start = new Date(startTime);
            Date end = new Date(endTime);
            return ResponseEntity.ok(degradationService.findByMeasurementTimeBetween(start, end));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", e.getMessage() != null ? e.getMessage() : "查询性能退化记录时发生错误"));
        }
    }

    /**
     * 查询剩余寿命低于指定阈值的记录
     */
    // @GetMapping("/by-remaining-life")
    // public ResponseEntity<?> findByRemainingLifeLessThan(
    //         @RequestParam Double threshold) {
    //     try {
    //         return ResponseEntity.ok(degradationService.findByRemainingLifePredictionLessThan(threshold));
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //         return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
    //                 .body(Map.of("error", e.getMessage() != null ? e.getMessage() : "查询性能退化记录时发生错误"));
    //     }
    // }
} 